import { render } from '@testing-library/react';
import { Dropdown, Menu, Modal, Table, TableProps } from 'antd';
import dayjs from 'dayjs';
import React from 'react';
import { User } from "../../types/User";
import {Link} from 'react-router-dom'
import { Pin } from 'components/pin';
import { useDeleteProject, useEditProject } from 'utils/project';
import { ButtonNoPadding } from 'components/lib';
import { useProjectModal, useProjectsQueryKey } from './util';
import { Project } from '../../types/Project';

interface ListProps extends TableProps<Project>{
  users: User[];
}

export const List = ({  users, ...props }: ListProps) => {

  const {mutate} = useEditProject(useProjectsQueryKey());
  const pinProject = (id: number) => (pin: boolean) => mutate({id, pin})
  
  return <Table rowKey={record => record.id} pagination={false} 
    columns={[
      {
        title: <Pin checked disabled/>,
        render(value, project) {
          return <Pin checked={project.pin} onCheckedChange={pin => pinProject(project.id)(pin)}/>
        }
      },
      {
        title: '名称',
        sorter: (a, b) => a.name.localeCompare(b.name),
        render(value, project) {
          return <Link to={String(project.id)}>{project.name}</Link>
        }
      }, 
      {
        title: '部门',
        dataIndex: 'organization',
        sorter: (a, b) => a.name.localeCompare(b.name)
      }, 
      {
        title: '负责人',
        render(value, project) {
          return <span>
            {users.find(user => user.id === project.personId)?.name || '未知'}
          </span>
        }
      },
      {
        title: '创建时间',
        render(value, project) {
          return <span>
            {project.created ? dayjs(project.created).format('YYYY-MM-DD') : '无'}
          </span>
        }
      }, 
      {
        render(value, project) {
          return <More project={project} />
        }
      }
    ]} 
    {...props}
  />
  
};

const More = ({project}: {project: Project}) => {
  const {startEdit} = useProjectModal();
  const editProject = (id: number) => () => startEdit(id)
  const {mutate: deleteProjects} = useDeleteProject(useProjectsQueryKey())
  const confirmDeleteProject = (id: number) => {
    return Modal.confirm({
      title: '确定删除这个项目?',
      content: '点击确定删除',
      okText: '确定',
      onOk() {
        deleteProjects({id})
      }
    })
  }

  return <Dropdown overlay={<Menu>
    <Menu.Item key={'edit'}>
      <ButtonNoPadding type={'link'} onClick={editProject(project.id)}>编辑</ButtonNoPadding>
    </Menu.Item>
    <Menu.Item key={'delete'}>
      <ButtonNoPadding type={'link'} onClick={() => {confirmDeleteProject(project.id)}}>删除</ButtonNoPadding>
    </Menu.Item>
  </Menu>}>
    <ButtonNoPadding type={'link'}>...</ButtonNoPadding>
  </Dropdown>
}
